package com.hl.controller;

import com.hl.domain.Company;
import com.hl.service.CompanyService;
import com.hl.util.R;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.List;
import java.util.Map;
import java.util.UUID;

@RestController
@RequestMapping("/company")
public class CompanyController {
    @Autowired
    private CompanyService companyService;

    //分页查询
    @GetMapping
    public R queryByPage(Integer pageNum,Integer pageSize){
        Map<String, Object> map = companyService.queryByPage(pageNum, pageSize);
        return  map!=null?R.success(map):R.fail(null);
    }

    //图片展示
    @GetMapping("/picture")
    public void picture(String fileName, HttpServletResponse response) throws IOException {
        FileInputStream in = new FileInputStream("d:\\picture\\" + fileName);
        ServletOutputStream out = response.getOutputStream();
        int len=0;
        byte[] bytes = new byte[1024 * 8];
        while ((len=in.read(bytes))!=-1){
            out.write(bytes,0,len);
        }
        in.close();
        out.close();

    }

    //动态条件查询
    @GetMapping("/search")
    public R search(Company company){
        Map<String, Object> map = companyService.querySelected(company);
        return map!=null?R.success(map):R.fail(null);
    }

    //图片上传
    @PostMapping("/upload")
    public R upload(MultipartFile multipartFile) throws IOException {
        String originalFilename = multipartFile.getOriginalFilename();
        String endStr=originalFilename.substring(originalFilename.lastIndexOf("."));
        String newFileName= UUID.randomUUID().toString().replace("-","")+endStr;
        File file = new File("d:\\picture\\" + newFileName);
        multipartFile.transferTo(file);
        return R.success("http://localhost:8080/company/picture?fileName="+newFileName);
    }

    //插入数据
    @PostMapping
    public R insertCompany(Company company){
        int row = companyService.insertCompany(company);
        return row>0?R.success(row):R.fail(0);
    }

    //修改数据
    @PutMapping
    public R update(@RequestBody Company company){
        int row = companyService.updateCompany(company);
        return row>0?R.success(row):R.fail(0);
    }


    //删除数据
    @DeleteMapping("/{id}")
    public R delete(@PathVariable Long id){
        int row = companyService.deleteCompany(id);
        return row>0?R.success(row):R.fail(0);
    }
    //通过id查询数据
    @GetMapping("/selectById")
    public R selectById(){
        return R.success(companyService.selectById());
    }
}
